const logger = require("./lib/logger");
const { spawn } = require("child_process");
const { resolve } = require("path");

logger.info("Starting GPIO logging visibility test...");

// 启动GPIO进程，确保启用IPC
const gpioProcess = spawn(`sudo`, [
  process.execPath,
  resolve(__dirname, "./lib/gpio.js"),
], {
  stdio: ['pipe', 'pipe', 'pipe', 'ipc'] // 添加IPC支持
});

logger.info("GPIO process started with IPC support");

// 设置事件处理器
gpioProcess.stderr.on("data", (data) => {
  const errorMsg = data.toString();
  logger.error(`[GPIO Server Error] ${errorMsg}`);
});

// 添加对子进程日志消息的处理
gpioProcess.on('message', (message) => {
  if (message && message.type === 'log') {
    // 根据日志级别调用相应的日志方法
    const logMessage = `[GPIO] ${message.message}`;
    switch (message.level) {
      case 'error':
        logger.error(logMessage);
        break;
      case 'warn':
        logger.warn(logMessage);
        break;
      case 'info':
        logger.info(logMessage);
        break;
      case 'debug':
        logger.debug(logMessage);
        break;
      default:
        logger.info(logMessage);
    }
  }
});

gpioProcess.stdout.on("data", (data) => {
  // 将stdout数据转发到日志
  const output = data.toString().trim();
  if (output) {
    logger.debug(`[GPIO stdout] ${output}`);
  }
});

gpioProcess.on('exit', (code, signal) => {
  logger.warn(`[GPIO Server] 进程退出，退出码: ${code}, 信号: ${signal}`);
});

gpioProcess.on('error', (error) => {
  logger.error('[GPIO Server] 进程错误:', error.message);
});

// 发送测试命令
logger.info("Sending test commands to GPIO process...");
setTimeout(() => {
  logger.info("Sending PWM command...");
  gpioProcess.stdin.write(`pwm 12 0.5\n`);
}, 1000);

setTimeout(() => {
  logger.info("Sending switch command...");
  gpioProcess.stdin.write(`sw 13 true\n`);
}, 2000);

// 关闭进程
setTimeout(() => {
  logger.info("Closing GPIO process...");
  gpioProcess.stdin.write(`exit\n`);
}, 4000);